/**
 * Created by luozhen on 2016/8/16.
 */
import java.sql.*;


/**
 * 数据库工具类
 * @author Administrator
 *
 */
public class DbUtil {

//    private String dbUrl="jdbc:mysql://localhost:3306/db_book"; // 数据库连接地址
//    private String dbUserName="root"; // 用户名
//    private String dbPassword="110625"; // 密码
//    private String jdbcName="com.mysql.jdbc.Driver"; // 驱动名称
//
//    /**
//     * 获取数据库连接
//     * @return
//     * @throws Exception
//     */
//    public Connection getCon()throws ClassNotFoundException, SQLException  {
//        Class.forName(jdbcName);
//        Connection con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
//        return con;
//    }



    /**
     * 关闭数据库连接
     * @param con
     * @throws Exception
     */
    public void closeCon(Connection con)throws Exception{
        if(con!=null){
            con.close();
        }
    }

    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sex;
        int id,grade;
        String url = "jdbc:mysql://localhost/db_book?"+"user=root&password=110625";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url);
            System.out.println("数据库连接成功！");
            pstmt = conn.prepareStatement("SELECT * FROM t_user");
            rs = pstmt.executeQuery();

            while(rs.next()){
                id=rs.getInt(1);
                sex=rs.getString(2);
                grade=rs.getInt(3);
                System.out.print("ID："+id);
                System.out.print(" 科目："+sex);
                System.out.println(" 成绩："+grade);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }finally{

        }

    }

    public void close(ResultSet rs,Statement st,Connection conn){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally{
                if(st != null){
                    try {
                        st.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } finally{
                        if(conn != null){
                            try {
                                conn.close();
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }

}
